package org.theflex.core{
	import flash.display.DisplayObject;
	
	import mx.controls.scrollClasses.ScrollBar;
	import mx.core.Application;
	import mx.core.Container;
	
	public class AutoScroll{
		public static function show(ui:DisplayObject):void{
			var topOffset:Number = ui.y;
			
			var parent:Container = ui.parent as Container;
			var verticalScroll:ScrollBar = parent.verticalScrollBar;
			
			while(verticalScroll == null && ! (parent is Application)){
				topOffset += parent.y;
				parent = parent.parent as Container;
				verticalScroll = parent.verticalScrollBar;
			}
			
			if(verticalScroll != null){
				var scrollHeight:Number = verticalScroll.maxScrollPosition;
				var visibleHeight:Number = parent.height;
				var visibleY:Number = visibleHeight + parent.verticalScrollPosition;
				
				if(parent.horizontalScrollBar) {
					visibleY -= parent.horizontalScrollBar.height;
				}
				
				if(topOffset < parent.verticalScrollPosition) {
					parent.verticalScrollPosition = topOffset - 10;
				}else if((ui.height + topOffset) - visibleY > 0){
					parent.verticalScrollPosition = Math.min(scrollHeight, parent.verticalScrollPosition + ((ui.height + topOffset) - visibleY)) + 10;
				}
			}
			
			if( ! (parent is Application)){
				show(parent);
			}
		}
	}
}